import { codeLogin, userInfo, refreshToken, updateLoginTime, tempLogin } from '@/api/user.js'
import { getStorageItem, setStorageItem, removeStorageItem } from "@/utils/storage.js"
import { TOKEN_KEY, TOKEN_REFRESH_KEY } from '@/utils/enum.js'

const getDefaultState = () => {
  return {
    token: getStorageItem(TOKEN_KEY) || '',
		userInfo: {},
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
	SET_USER_INFO: (state, userInfo) => {
		state.userInfo = userInfo
	},
}

// 设置token
function setToken(token, refreshToken) {
	setStorageItem(TOKEN_KEY, token)
	refreshToken && setStorageItem(TOKEN_REFRESH_KEY, refreshToken)
}

const actions = {
	// code登录
	codeLogin({ commit }, code) {
		return new Promise((resolve, reject) => {
			codeLogin({ code }).then(response => {
				const { token, nickName, headImgUrl } = response.data
				commit('SET_TOKEN', token)
				commit('SET_USER_INFO', { nickname: nickName, avatar: headImgUrl })
				setToken(token)
				resolve(token)
			}).catch(error => {
				reject(error)
			})
		})
	},
	// 临时登录
	tempLogin({ commit }) {
		return new Promise((resolve, reject) => {
			tempLogin({ userId: 1 }).then(response => {
				const token = response.msg
				commit('SET_TOKEN', token)
				setToken(token)
				resolve(token)
			}).catch(error => {
				reject(error)
			})
		})
	},
	// 用户信息
	getUserInfo({ commit }) {
		return new Promise((resolve, reject) => {
			userInfo().then(response => {
				commit('SET_USER_INFO', response.data)
				resolve(response.data)
			}).catch(error => {
				reject(error)
			})
		})
	},
	// 刷新token
	refreshToken({ commit }) {
		return new Promise((resolve, reject) => {
			refreshToken().then(response => {
				const { token } = response.data
				commit('SET_TOKEN', token)
				setToken(token)
				resolve(token)
			}).catch(error => {
				reject(error)
			})
		})
	},
	// remove token
	resetToken({ commit }) {
		return new Promise(resolve => {
			removeStorageItem(TOKEN_KEY)
			removeStorageItem(TOKEN_REFRESH_KEY)
			commit('RESET_STATE')
			resolve()
		})
	}
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

